package com.company.algo.niuke;

import java.util.*;


/**华为：表达式求值
 请写一个整数计算器，支持加减乘三种运算和括号。
 es:
 输入"(2*(3-4))*5"，返回值-10
 输入"3+2*3*4-1"，返回值26
 */
public class ExpressionEvaluation2 {
    Map<Character, Integer> map = new HashMap<Character, Integer>(){{
        put('-', 1);
        put('+', 1);
        put('*', 2);
        put('/', 2);
        put('%', 2);
        put('^', 3);
    }};
    public int calculate(String s) {
        s = s.replaceAll(" ", "");
        char[] cs = s.toCharArray();
        int n = s.length();
        Stack<Integer> nums = new Stack<>();
        nums.push(0);
        Stack<Character> ops = new Stack<>();
        for (int i = 0; i < n; i++) {
            char c = cs[i];
            if (isNumber(c)) {
                int num = 0 , j = i;
                while(j < n && Character.isDigit(cs[j])){
                    num = 10 * num + (cs[j++] - '0');
                }
                nums.push(num);
                i = j - 1;
            } else if (c == '(') {
                ops.push(c);
            } else if (c == ')') {
                while(!ops.isEmpty() && ops.peek()!='(')
                    calc(nums,ops);
                ops.pop();
            } else {
                //这一段才是实现乘除法优先级的核心逻辑
                while(!ops.isEmpty() && ops.peek()!='('
                        && map.get(ops.peek())>=map.get(c))
                    calc(nums,ops);
                ops.push(c);
            }
        }
        calc(nums, ops);
        return nums.isEmpty()? 0: nums.peek();
    }
    private void calc(Stack<Integer> nums, Stack<Character> ops){
        if(nums.size() < 2 || ops.isEmpty()) return;
        Character op = ops.pop();
        //注意先弹出b，再弹出a
        int b = nums.pop();
        int a = nums.pop();
        int res = 0;
        switch(op){
            case '+':
                res = a + b;
                break;
            case '-':
                res = a - b;
                break;
            case '*':
                res = a * b;
                break;
            case '/':
                res = a / b;
                break;
            case '%':
                res = a % b;
                break;
            case '^':
                res = (int)Math.pow(a,b);
                break;
        }
        nums.push(res);
    }
    boolean isNumber(char c) {
        return Character.isDigit(c);
    }


    public static void main(String[] args) {
        ExpressionEvaluation2 Main = new ExpressionEvaluation2();
        System.out.println(Main.calculate("(3+4)*(5+(2-3))"));
    }

}
